<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of login
 *
 * @author Admin
 */
class login extends MY_Controller {

	public function index() {
		$ref = request('ref') != '' ? base_url(request('ref')) : url_create('admin');

		if (preg_match('/' . addcslashes(url_create('admin', 'login'), '/.\\*+[])(|?^') . '/i', $ref) != 0)
			$ref = url_create('admin');

		if ($this->isUserLogin())
			redirect($ref);

		if (isset($_POST['username'])) {
			$this->load->helper('form');
			$this->load->library('form_validation');

			$this->form_validation->set_rules('username', 'username', 'required');
			$this->form_validation->set_rules('password', 'password', 'required');

			if (!$this->form_validation->run()) {
				$json['state'] = 'error';
				$json['message'] = lang('login_invalid');
				echo json_encode($json);
			} else {
				$username = $this->input->post('username');
				$password = $this->input->post('password');
				$remember = $this->input->post('remember');
				if ($this->loginUser($username, $password, $remember)) {
					$json['state'] = 'success';
					$json['message'] = lang('login_success');
					echo json_encode($json);
				} else {
					$json['state'] = 'error';
					$json['message'] = lang('login_fail');
					echo json_encode($json);
				}
			}
		} else {
			$this->data['reference'] = $ref;
			$this->data['temp'] = 'admin/login/index';
			$this->load->view('admin/login/layout', $this->data);
		}
	}

	protected function loginUser($username, $password, $remember = 0) {
		$this->load->model('model_user');
		$userInfo = $this->model_user->get_info_rule(array(
			'username' => $username,
			'password' => md5($password)
				));
		if ($userInfo !== FALSE) {
			$this->user = $userInfo;
			$this->session->set_userdata('user_id', $userInfo->id);
			if(!$remember)
			{
				
			}
			return TRUE;
		}
		$this->session->set_userdata('user_id',$this->siteConfig->guest_id);
		$this->getUserInfo();
		return FALSE;
	}

}

?>
